﻿local Orig_AuctionFrameBrowse_Update = nil
local Orig_GetAuctionItemInfo = nil
local B_AST_OldText = nil
local B_AST_QueryAuctionItems_Old = nil
local B_AST_TimerFrame = nil
local B_AST_TimeLeft = nil
local B_AST_LastTime = nil
local S_AH_Frame = CreateFrame("Frame")
S_AH_Frame:RegisterEvent("AUCTION_HOUSE_SHOW")
S_AH_Frame:SetScript("OnEvent", function()
	if event == "AUCTION_HOUSE_SHOW" and IsAddOnLoaded("Blizzard_AuctionUI") then
		if not Orig_AuctionFrameBrowse_Update then 
			Orig_AuctionFrameBrowse_Update = AuctionFrameBrowse_Update
			AuctionFrameBrowse_Update = S_AH_AuctionFrameBrowse_Update

			Orig_BrowseButton_OnClick = BrowseButton_OnClick
			BrowseButton_OnClick = S_AH_BrowseButton_OnClick
			
			Orig_GetAuctionItemInfo = GetAuctionItemInfo
			GetAuctionItemInfo = S_AH_ShowBid_GetAuctionItemInfo
			
			B_AST_QueryAuctionItems_Old = QueryAuctionItems
			QueryAuctionItems = B_AST_QueryAuctionItems_New
			
			B_AST_OldText = BrowseSearchButton:GetText()
			
			if ShowOnPlayerCheckButton:GetChecked() then
				ShowOnPlayerCheckButton:SetChecked(false)
			end
		end
	end
end)

--单价：覆盖AuctionFrameBrowse_Update的功能
function S_AH_AuctionFrameBrowse_Update()
	local numBatchAuctions, totalAuctions = GetNumAuctionItems("list");
	local button, buttonName, iconTexture, itemName, color, itemCount, moneyFrame, buyoutMoneyFrame, buyoutText, buttonHighlight;
	local offset = FauxScrollFrame_GetOffset(BrowseScrollFrame);
	local index;
	local isLastSlotEmpty;
	local name, texture, count, quality, canUse, minBid, minIncrement, buyoutPrice, duration, bidAmount, highBidder, owner;
	BrowseBidButton:Disable();
	BrowseBuyoutButton:Disable();
	-- Update sort arrows
	SortButton_UpdateArrow(BrowseQualitySort, "list", "quality");
	SortButton_UpdateArrow(BrowseLevelSort, "list", "level");
	SortButton_UpdateArrow(BrowseDurationSort, "list", "duration");
	SortButton_UpdateArrow(BrowseHighBidderSort, "list", "status");
	SortButton_UpdateArrow(BrowseCurrentBidSort, "list", "bid")
	
	-- Show the no results text if no items found
	if ( numBatchAuctions == 0 ) then
		BrowseNoResultsText:Show();
	else
		BrowseNoResultsText:Hide();
	end

	for i=1, NUM_BROWSE_TO_DISPLAY do
		index = offset + i + (NUM_AUCTION_ITEMS_PER_PAGE * AuctionFrameBrowse.page);
		button = getglobal("BrowseButton"..i);
		-- Show or hide auction buttons
		if ( index > (numBatchAuctions + (NUM_AUCTION_ITEMS_PER_PAGE * AuctionFrameBrowse.page)) ) then
			button:Hide();
			-- If the last button is empty then set isLastSlotEmpty var
			if ( i == NUM_BROWSE_TO_DISPLAY ) then
				isLastSlotEmpty = 1;
			end
		else
			button:Show();

			buttonName = "BrowseButton"..i;
			name, texture, count, quality, canUse, level, minBid, minIncrement, buyoutPrice, bidAmount, highBidder, owner =  GetAuctionItemInfo("list", offset + i);
			
			--显示剩余时间
			duration = GetAuctionItemTimeLeft("list", offset + i);
			if duration == 1 then timeleft = RED_FONT_COLOR_CODE .. "<30m|r"
			elseif duration == 2 then timeleft = NORMAL_FONT_COLOR_CODE .. "30m-2h|r"
			elseif duration == 3 then timeleft = GREEN_FONT_COLOR_CODE .. "2-8h|r"
			elseif duration == 4 then timeleft = GRAY_FONT_COLOR_CODE .. ">8h|r"
			end
			-- Resize button if there isn't a scrollbar
			buttonHighlight = getglobal("BrowseButton"..i.."Highlight");
			if ( numBatchAuctions <= NUM_BROWSE_TO_DISPLAY ) then
				button:SetWidth(625);
				buttonHighlight:SetWidth(589);
				BrowseCurrentBidSort:SetWidth(207);
			else
				button:SetWidth(600);
				buttonHighlight:SetWidth(562);
				BrowseCurrentBidSort:SetWidth(184);
			end
			-- Set name and quality color
			color = ITEM_QUALITY_COLORS[quality];
			itemName = getglobal(buttonName.."Name");
			itemName:SetText(name);
			itemName:SetVertexColor(color.r, color.g, color.b);
			-- Set level
			if ( level > UnitLevel("player") ) then
				getglobal(buttonName.."Level"):SetText(RED_FONT_COLOR_CODE..level..FONT_COLOR_CODE_CLOSE);
			else
				getglobal(buttonName.."Level"):SetText(level);
			end
			-- Set closing time
			getglobal(buttonName.."ClosingTimeText"):SetText(timeleft);
			getglobal(buttonName.."ClosingTime").tooltip = AuctionFrame_GetTimeLeftTooltipText(duration);
			-- Set item texture, count, and usability
			iconTexture = getglobal(buttonName.."ItemIconTexture");
			iconTexture:SetTexture(texture);
			if ( not canUse ) then
				iconTexture:SetVertexColor(1.0, 0.1, 0.1);
			else
				iconTexture:SetVertexColor(1.0, 1.0, 1.0);
			end
			itemCount = getglobal(buttonName.."ItemCount");
			if ( count > 1 ) then
				itemCount:SetText(count);
				itemCount:Show();
			else
				itemCount:Hide();
			end
			-- Set high bid
			moneyFrame = getglobal(buttonName.."MoneyFrame");
			yourBidText = getglobal(buttonName.."YourBidText");
			buyoutMoneyFrame = getglobal(buttonName.."BuyoutMoneyFrame");
			buyoutText = getglobal(buttonName.."BuyoutText");
			-- If not bidAmount set the bid amount to the min bid
			if ( bidAmount == 0 ) then
				if S_AH_PricePerUnitCheckButton:GetChecked() then
					MoneyFrame_Update(moneyFrame:GetName(), Round(minBid/count))
				else
					MoneyFrame_Update(moneyFrame:GetName(), minBid)
				end
			else
				if S_AH_PricePerUnitCheckButton:GetChecked() then
					MoneyFrame_Update(moneyFrame:GetName(), Round(bidAmount/count))
				else
					MoneyFrame_Update(moneyFrame:GetName(), bidAmount)
				end
			end

			if ( highBidder ) then
				yourBidText:Show();
			else
				yourBidText:Hide();
			end

			if ( buyoutPrice > 0 ) then
				moneyFrame:SetPoint("RIGHT", buttonName, "RIGHT", 10, 10);
				if S_AH_PricePerUnitCheckButton:GetChecked() then
					MoneyFrame_Update(buyoutMoneyFrame:GetName(), Round(buyoutPrice/count))
				else
					MoneyFrame_Update(buyoutMoneyFrame:GetName(), buyoutPrice)
				end
				buyoutMoneyFrame:Show();
				buyoutText:Show();
			else
				moneyFrame:SetPoint("RIGHT", buttonName, "RIGHT", 10, 3);
				buyoutMoneyFrame:Hide();
				buyoutText:Hide();
			end
			-- Set high bidder
			--if ( not highBidder ) then
			--	highBidder = RED_FONT_COLOR_CODE..NO_BIDS..FONT_COLOR_CODE_CLOSE;
			--end
			getglobal(buttonName.."HighBidder"):SetText(owner);
			-- Set highlight
			if ( GetSelectedAuctionItem("list") and (offset + i) == GetSelectedAuctionItem("list") ) then
				button:LockHighlight();
				
				if ( buyoutPrice > 0 and buyoutPrice >= minBid and GetMoney() >= buyoutPrice ) then
					BrowseBuyoutButton:Enable();
					AuctionFrame.buyoutPrice = buyoutPrice;
				else
					AuctionFrame.buyoutPrice = nil;
				end
				-- Set bid
				if ( bidAmount > 0 ) then
					bidAmount = bidAmount + minIncrement ;
					MoneyInputFrame_SetCopper(BrowseBidPrice, bidAmount);
				else
					MoneyInputFrame_SetCopper(BrowseBidPrice, minBid);
				end

				if ( not highBidder and GetMoney() >= MoneyInputFrame_GetCopper(BrowseBidPrice) ) then
					BrowseBidButton:Enable();
				end
			else
				button:UnlockHighlight();
			end
		end
	end

	-- Update scrollFrame
	-- If more than one page of auctions show the next and prev arrows when the scrollframe is scrolled all the way down
	if ( totalAuctions > NUM_AUCTION_ITEMS_PER_PAGE ) then
		if ( isLastSlotEmpty ) then
			BrowsePrevPageButton:Show();
			BrowseNextPageButton:Show();
			BrowseSearchCountText:Show();
			local itemsMin = AuctionFrameBrowse.page * NUM_AUCTION_ITEMS_PER_PAGE + 1;
			local itemsMax = itemsMin + numBatchAuctions - 1;
			BrowseSearchCountText:SetText(format(NUMBER_OF_RESULTS_TEMPLATE, itemsMin, itemsMax, totalAuctions ));
			if ( AuctionFrameBrowse.page == 0 ) then
				BrowsePrevPageButton.isEnabled = nil;
			else
				BrowsePrevPageButton.isEnabled = 1;
			end
			if ( AuctionFrameBrowse.page == (ceil(totalAuctions/NUM_AUCTION_ITEMS_PER_PAGE) - 1) ) then
				BrowseNextPageButton.isEnabled = nil;
			else
				BrowseNextPageButton.isEnabled = 1;
			end
		else
			BrowsePrevPageButton:Hide();
			BrowseNextPageButton:Hide();
			BrowseSearchCountText:Hide();
		end
		
		-- Artifically inflate the number of results so the scrollbar scrolls one extra row
		numBatchAuctions = numBatchAuctions + 1;
	else
		BrowsePrevPageButton:Hide();
		BrowseNextPageButton:Hide();
		BrowseSearchCountText:Hide();
	end
	FauxScrollFrame_Update(BrowseScrollFrame, numBatchAuctions, NUM_BROWSE_TO_DISPLAY, AUCTIONS_BUTTON_HEIGHT);
end

function S_AH_BrowseButton_OnClick(button)
	if ( not button ) then
		button = this
	end
	SetSelectedAuctionItem("list", button:GetID() + FauxScrollFrame_GetOffset(BrowseScrollFrame))
	S_AH_AuctionFrameBrowse_Update()
end

--竞标：覆盖GetAuctionItemInfo的功能
function S_AH_ShowBid_GetAuctionItemInfo(list, offset_i)
	local name, texture, count, quality, canUse, level, minBid, minIncrement, buyoutPrice, bidAmount, highBidder, owner =  Orig_GetAuctionItemInfo(list, offset_i);

	if ( (list == "list") and (bidAmount > 0) ) then
		-- Shorten long names
		if (string.len(name) > 30) then
				name = string.sub(name, 0, 28) .. "...";
		end
		name = name .. " |cffffff00(竞标)|r";
	end

	return name, texture, count, quality, canUse, level, minBid, minIncrement, buyoutPrice, bidAmount, highBidder, owner;
end

--搜索的间隔时间
function B_AST_QueryAuctionItems_New(a,b,c,d,e,f,g,h,i,j)
	if (CanSendAuctionQuery()) then
		B_AST_StartTimer()
	end
	B_AST_QueryAuctionItems_Old(a,b,c,d,e,f,g,h,i,j)
end

function B_AST_StartTimer()
	B_AST_TimeLeft = 5
	B_AST_LastTime = GetTime()
	S_AH_Frame:SetScript("OnUpdate", B_AST_OnUpdate)
end

function B_AST_StopTimer()
	S_AH_Frame:SetScript("OnUpdate", nil)
	BrowseSearchButton:SetText(B_AST_OldText)
end

function B_AST_OnUpdate()
	if (CanSendAuctionQuery()) then
		B_AST_StopTimer()
	else
		local t = GetTime()
		local td = t - B_AST_LastTime
		B_AST_TimeLeft = B_AST_TimeLeft - td
		
		if B_AST_TimeLeft < 0 then
			B_AST_TimeLeft = 0
		end

		local text = math.floor(B_AST_TimeLeft * 10) / 10
		if string.len(text) == 1 then
			text = text .. ".0"
		end
		BrowseSearchButton:SetText(text)
		
		B_AST_LastTime = t
	end
end

hooksecurefunc("AuctionFrame_LoadUI", function()
	--稀有程度
	BrowseDropDown:ClearAllPoints()
	BrowseDropDown:SetParent(AuctionFrameBrowse)
	BrowseDropDown:SetPoint("TOPLEFT", BrowseLevelText, "BOTTOMRIGHT", 10, 5)
	UIDropDownMenu_SetWidth(50, BrowseDropDown)

	--可用物品
	BrowseIsUsableText:ClearAllPoints()
	BrowseIsUsableText:SetParent(AuctionFrameBrowse)
	BrowseIsUsableText:SetPoint("LEFT", BrowseDropDown, "RIGHT", 0, -5)

	--试穿效果
	BrowseShowOnCharacterText:ClearAllPoints()
	BrowseShowOnCharacterText:SetParent(AuctionFrameBrowse)
	BrowseShowOnCharacterText:SetPoint("LEFT", BrowseDropDown, "RIGHT", 0, 15)

	--搜索
	BrowseSearchButton:ClearAllPoints()
	BrowseSearchButton:SetParent(AuctionFrameBrowse)
	BrowseSearchButton:SetPoint("LEFT", IsUsableCheckButton, "RIGHT", 20, 12)
	BrowseSearchButton:SetWidth(60)
	BrowseSearchButton:SetHeight(25)
	
	--重置
	local S_AH_ResetButton = CreateFrame("Button", nil, nil, "UIPanelButtonTemplate")
	S_AH_ResetButton:SetParent(AuctionFrameBrowse)
	S_AH_ResetButton:SetWidth(60)
	S_AH_ResetButton:SetHeight(25)
	S_AH_ResetButton:SetText("重置")
	S_AH_ResetButton:SetFont(STANDARD_TEXT_FONT, 14)
	S_AH_ResetButton:SetPoint("LEFT", BrowseSearchButton, "RIGHT", 5, 0)
	S_AH_ResetButton:Show()
	S_AH_ResetButton:SetScript("OnClick", function()
		PlaySound("igMainMenuOptionCheckBoxOn")
		BrowseName:SetText("")
		BrowseMinLevel:SetText("")
		BrowseMaxLevel:SetText("")
		BrowseSearchCountText:SetText("")
		IsUsableCheckButton:SetChecked(false)
		if ShowOnPlayerCheckButton:GetChecked() then
			ShowOnPlayerCheckButton:SetChecked(false)
		end
		S_AH_PricePerUnitCheckButton:SetChecked(false)
		UIDropDownMenu_SetSelectedValue(BrowseDropDown, -1)
		AuctionFrameBrowse.selectedClass            = nil
		AuctionFrameBrowse.selectedClassIndex       = nil
		AuctionFrameBrowse.selectedSubclass         = nil
		AuctionFrameBrowse.selectedSubclassIndex    = nil
		AuctionFrameBrowse.selectedInvtype          = nil
		AuctionFrameBrowse.selectedInvtypeIndex     = nil
		AuctionFrameBrowse.page = 0
		for i=1, NUM_BROWSE_TO_DISPLAY do
			getglobal("BrowseButton"..i):Hide()
		end
		BrowsePrevPageButton:Hide()
		BrowseNextPageButton:Hide()		
		BrowseScrollFrame:Hide()
		AuctionFrameFilters_Update()
	end)
	
	--显示单价
	local S_AH_PricePerUnitCheckButton = CreateFrame("CheckButton", "S_AH_PricePerUnitCheckButton", AuctionFrameBrowse, "UICheckButtonTemplate")
	S_AH_PricePerUnitCheckButton:SetParent(AuctionFrameBrowse)
	S_AH_PricePerUnitCheckButton:SetWidth(25)
	S_AH_PricePerUnitCheckButton:SetHeight(25)
	S_AH_PricePerUnitCheckButton:SetPoint("LEFT", S_AH_ResetButton, "RIGHT", 15, 0)
	S_AH_PricePerUnitCheckButton:Show()
	S_AH_PricePerUnitCheckButton.text = S_AH_PricePerUnitCheckButton:CreateFontString("Status", "LOW", "GameFontNormal")
	S_AH_PricePerUnitCheckButton.text:SetPoint("LEFT", S_AH_PricePerUnitCheckButton, "RIGHT", 5, 0)
	S_AH_PricePerUnitCheckButton.text:SetText("显示单价")
	S_AH_PricePerUnitCheckButton:SetScript("OnClick", S_AH_AuctionFrameBrowse_Update)
end)